#include "ResourceMgr.h"
#include "SDL_image.h"
#include "SFont.h"
#include <iostream>
using namespace std;

ResourceMgr *ResourceMgr::instance_ = NULL;

ResourceMgr::~ResourceMgr () {
	for (vector<Resource *>::iterator itr = resources_.begin();
						itr != resources_.end();
						itr++)
	{
			Resource *resource = *itr;
			destroy (resource);
	}
}

SDL_Surface *
ResourceMgr::
getGfx (const string& name, bool cache, bool no_dispformat) {
	Resource *resource;
	if ((resource = find(name)) == NULL) {
		if (cache) {
				resource = new Resource;
				resource->id 		= string(name);
				resource->type = RESOURCE_GFX;
				resources_.push_back(resource);
		}
		string fullPath(path_);
		fullPath += "/gfx/";
		fullPath += name;
		cout << ">>> Loading new Gfx resource: " << fullPath << endl;
		SDL_Surface *tmp = IMG_Load(fullPath.c_str());
		if (tmp == NULL) {
			cerr << "Cannot access GFX resource: " << fullPath.c_str() << endl;
			SDL_Quit();
			exit (-1);
		}
		if (cache) {
				if (!no_dispformat) {
						resource->data = SDL_DisplayFormat(tmp);
						SDL_FreeSurface(tmp);
				}
				else {
						resource->data = tmp;
				}
		}
		else {
				if (!no_dispformat) {
						return SDL_DisplayFormat(tmp);
				}
				else {
						return tmp;
				}
		}
	}
	else {
		cout << ">>> Resource \"" << name << "\" found in cache" << endl;
	}
	return (SDL_Surface *)resource->data;
}

SFont_Font *
ResourceMgr::
getFont (const string& name) {
	Resource *resource;
	if ((resource = find(name)) == NULL) {
		// Note that we pass "false" to the getGfx function so that the resource
		// is not added to the resource list (called "cache")
		// Also, we pass "true" to the optional parameter "no_dispformat" because
		// SFont would behave in a strange way.
		SDL_Surface *fontSurface = ResourceMgr::instance()->getGfx(name, false, true);
		resource = new Resource;
		resource->id   = string(name);
		resource->type = RESOURCE_FONT;
		resource->data = SFont_InitFont(fontSurface);
		// The real resource with name "name" is an SFont_Font*
		resources_.push_back(resource);
		cout << ">>> Loading new Bitmap font resource: " << name << endl;
	}
	else {
		cout << ">>> Resource \"" << name << "\" found in cache" << endl;
	}
	return (SFont_Font *)resource->data;
}

ResourceMgr::Resource *
ResourceMgr::
find (const string& id) {
	// If the resource is already in the cache, return it
	for (vector<Resource *>::iterator itr = resources_.begin();
						itr != resources_.end();
						itr++)
	{
		Resource *resource = *itr;
		if (resource->id.compare(id) == 0) {
			return resource;
		}
	}
	return NULL;
}

void
ResourceMgr::
destroy (const string& id) {
	Resource *resource = find(id);
	if (resource != NULL) {
		destroy(resource);
	}
}

void
ResourceMgr::
destroy (Resource *resource) {
		
		// NO !!!
		//resources_.erase(resources_.begin()+resource->index);
		delete resource;
}

